from deepseek_model import DeepSeekModel, ModelLoadError
import speech_recognition as sr
import os
import platform
import subprocess
import logging
import pyttsx3
import threading
import time
import sys

class AudioDeviceError(Exception):
    """音频设备异常"""
    pass

class TTSConversionError(Exception):
    """语音合成异常"""
    pass

class AudioVisualizer(threading.Thread):
    """音频输入可视化线程"""
    def __init__(self):
        super().__init__()
        self._running = False
        self.frames = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█']
        self.daemon = True  # 设为守护线程

    def run(self):
        self._running = True
        while self._running:
            for i in range(len(self.frames)):
                if not self._running:
                    break
                sys.stdout.write('\r正在聆听: ' + ''.join(self.frames[:i+1]))
                sys.stdout.flush()
                time.sleep(0.1)
            sys.stdout.write('\r' + ' ' * 20 + '\r')  # 清空当前行
            sys.stdout.flush()

    def stop(self):
        self._running = False
        time.sleep(0.2)  # 等待动画完成
        sys.stdout.write('\r' + ' ' * 20 + '\r')  # 清空动画行
        sys.stdout.flush()

class DeepSeekAssistant:
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.model = DeepSeekModel()
        self.recognizer = sr.Recognizer()
        self.visualizer = AudioVisualizer()

        # 检测麦克风设备
        try:
            self.microphone = sr.Microphone()
            if not self.microphone.list_microphone_names():
                raise AudioDeviceError("未检测到可用麦克风")
        except Exception as e:
            raise AudioDeviceError(f"麦克风初始化失败: {str(e)}")

        # 检测播放器
        self.os_type = platform.system()
        if self.os_type == "Windows":
            self.player_cmd = "start"
        else:
            try:
                subprocess.run(["which", "mpg123"], check=True)
                self.player_cmd = "mpg123"
            except:
                raise AudioDeviceError("需要安装mpg123 (Linux/Mac) 或配置默认播放器 (Windows)")

        # 初始化 TTS 引擎
        self.tts_engine = pyttsx3.init()
        voices = self.tts_engine.getProperty('voices')
        for voice in voices:
            if 'chinese' in voice.name.lower():
                self.tts_engine.setProperty('voice', voice.id)
                break

    def initialize(self):
        try:
            self.model.load_model()
        except ModelLoadError as e:
            self.logger.error(str(e))
            raise

    def process_query(self, query):
        return self.model.generate_response(query)

    def speak(self, text):
        try:
            self.tts_engine.say(text)
            self.tts_engine.runAndWait()
        except Exception as e:
            raise TTSConversionError(f"语音合成失败: {str(e)}")

    def listen(self):
        try:
            with self.microphone as source:
                self.recognizer.adjust_for_ambient_noise(source)
                self.logger.info("请开始说话（5秒超时）...")
                
                # 启动可视化线程
                self.visualizer = AudioVisualizer()
                self.visualizer.start()
                
                audio = self.recognizer.listen(source, timeout=5)
                self.visualizer.stop()
                return self.recognizer.recognize_google(audio, language='zh-CN')
        except sr.WaitTimeoutError:
            self.visualizer.stop()
            self.logger.warning("未检测到语音输入")
            return ""
        except sr.UnknownValueError:
            self.visualizer.stop()
            self.logger.warning("无法识别语音内容")
            return ""
